import { route } from 'quasar/wrappers';
import {
  createMemoryHistory,
  createRouter,
  createWebHashHistory,
  createWebHistory,
} from 'vue-router';
import routes from './routes';
import { LoadingBar } from 'quasar'
import type { RouteLocationNormalized } from 'vue-router';
import { useAuthStore, useLayoutStore } from 'src/stores/layout-store';

/*
 * If not building with SSR mode, you can
 * directly export the Router instantiation;
 *
 * The function below can be async too; either use
 * async/await or return a Promise which resolves
 * with the Router instance.
 */

export default route(function (/* { store, ssrContext } */) {
  const createHistory = process.env.SERVER
    ? createMemoryHistory
    : (process.env.VUE_ROUTER_MODE === 'history' ? createWebHistory : createWebHashHistory);

  const Router = createRouter({
    scrollBehavior: () => ({ left: 0, top: 0 }),
    routes,

    // Leave this as is and make changes in quasar.conf.js instead!
    // quasar.conf.js -> build -> vueRouterMode
    // quasar.conf.js -> build -> publicPath
    history: createHistory(
      process.env.MODE === 'ssr' ? void 0 : process.env.VUE_ROUTER_BASE
    ),
  });

  /* 数组里面的URL里面无需鉴权 */
  const notCheckPath = ['/login'];

  // 路由跳转前置拦截器
  Router.beforeEach((to: RouteLocationNormalized, form: RouteLocationNormalized, next) => {
    LoadingBar.start()
    console.log('form: ', form);
    console.log('to: ', to);
    const auth = useAuthStore();
    const layout = useLayoutStore();
    if (notCheckPath.indexOf(to.fullPath) > -1) {
      next()
    } else {
      // 不存在则跳转到登录页面
      if (auth.token) {
        if (to.fullPath === '/') {
          // 切换面包屑
          layout.crumbsList = [layout.mainPage]
        } else {
          const item = to.query.url ?
            layout.menuPathMap.get(to.query.url as string) :
            layout.menuPathMap.get(to.fullPath)
          console.log('layout.menuPathMap: ', layout.menuPathMap);
          console.log('item: ', item);
          if (item) {
            // 切换面包屑
            layout.crumbsList = layout.findP(item)
            // 增加Tab栏
            if (layout.tabList.filter(i => i.id === item.id).length === 0) {
              layout.tabList.push(item);
            }
          }

        }
        next()
      } else {
        next({ path: '/login' })
      }
    }
  })

  // 路由跳转之后的回调
  Router.afterEach(() => {
    console.log('afterEach: ');

    LoadingBar.stop()
    LoadingBar.stop()
  })

  return Router;
});
